<template>
  <div class="app-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/monitor/monitorhost' }">主机监控</el-breadcrumb-item>
        <el-breadcrumb-item>{{ activeTab === 'overview' ? '主机概览' : '监控图表' }}</el-breadcrumb-item>
        <el-breadcrumb-item>{{ hostInfo.name || '主机详情' }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 顶部选项卡 -->
    <div class="tab-header">
      <div class="tab-buttons">
        <el-button 
          :type="activeTab === 'overview' ? 'primary' : ''" 
          @click="switchTab('overview')"
          class="tab-button"
        >
          主机概览
        </el-button>
        <el-button 
          :type="activeTab === 'chart' ? 'primary' : ''" 
          @click="switchTab('chart')"
          class="tab-button"
        >
          监控图表
        </el-button>
      </div>
      <!-- 主机状态信息居右 -->
      <div class="host-status">
        <div class="agent-status">
          <el-tag :type="hostInfo.agentOnlineStatus === '0' ? 'success' : 'danger'" size="small">
            {{ hostInfo.agentOnlineStatus === '0' ? '在线' : '离线' }}
          </el-tag>
          <span class="agent-version">探针版本：{{ hostInfo.agentVersion || '-' }}</span>
          <span class="update-time">更新时间: {{ formatUpdateTime(hostInfo.updateTime) }}</span>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          plain
          icon="Back"
          @click="handleBack"
        >返回</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="Refresh"
          @click="refreshData"
          :loading="loading"
        >刷新</el-button>
      </el-col>
    </el-row>

    <!-- 主机概览内容 -->
    <div v-if="activeTab === 'overview'" class="detail-content">
      <el-row :gutter="32">
        <el-col :span="8">
          <!-- 主机信息卡片 -->
          <el-card class="info-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">主机信息</span>
              </div>
            </template>
            <div class="info-list">
              <div class="info-item">
                <span class="label">名称：</span>
                <span class="value">{{ hostInfo.name || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">地址：</span>
                <span class="value">{{ hostInfo.address || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">CPU型号：</span>
                <span class="value">{{ hostAttr.cpuModel || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">CPU：</span>
                <span class="value">{{ hostAttr.cpuCore || '-' }}核</span>
              </div>
               <div class="info-item">
                <span class="label">CPU速率：</span>
                <span class="value">{{ hostAttr.cpuFrequency || '-' }}GHZ</span>
              </div>
              <div class="info-item">
                <span class="label">内存大小：</span>
                <span class="value">{{ hostAttr.memorySize || '-' }}GB</span>
              </div>
              <div class="info-item">
                <span class="label">磁盘大小：</span>
                <span class="value">{{ hostAttr.diskSize || '-' }}GB</span>
              </div>
              <div class="info-item">
                <span class="label">探针标识：</span>
                <span class="value">{{ hostInfo.agentKey || '-' }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <!-- CPU卡片 -->
          <el-card class="monitor-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">CPU</span>
                <span class="card-subtitle">总计 {{ monitorHost.cpuUsage || 0 }}%</span>
              </div>
            </template>
            <div class="cpu-content">
              <div class="cpu-item">
                <div class="cpu-label">用户态</div>
                <el-progress :percentage="monitorHost.cpuUserUsage || 0" :color="getCpuColor(monitorHost.cpuUserUsage)" :show-text="true" />
              </div>
              <div class="cpu-item">
                <div class="cpu-label">内核态</div>
                <el-progress :percentage="monitorHost.cpuSystemUsage || 0" :color="getCpuColor(monitorHost.cpuSystemUsage)" :show-text="true" />
              </div>
            </div>
          </el-card>
          <!-- 连接数卡片 -->
          <el-card class="info-card" style="margin-top:24px;">
            <template #header>
              <div class="card-header">
                <span class="card-title">连接数</span>
              </div>
            </template>
            <div class="connection-content">
              <div class="connection-item">TCP: {{ monitorHost.tcpConnections || 0 }}</div>
              <div class="connection-item">UDP: {{ monitorHost.udpConnections || 0 }}</div>
              <div class="connection-item total">总计: {{ monitorHost.totalConnections || 0 }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <!-- 内存卡片 -->
          <el-card class="monitor-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">内存</span>
              </div>
            </template>
            <div class="memory-content">
              <div class="memory-main">
                <div class="memory-info">
                  <div class="memory-used">{{ monitorHost.memoryUsed || '0.00' }} GB</div>
                  <div class="memory-percent">{{ monitorHost.memoryUsage || '0.00' }}%</div>
                </div>
                <el-progress type="dashboard" :percentage="monitorHost.memoryUsage || 0" :color="getMemoryColor(monitorHost.memoryUsage)" width="120" />
              </div>
              <div class="memory-total">总计 {{ monitorHost.memoryTotal || '0.00' }} GB</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="32" style="margin-top:32px;">
        <el-col :span="6">
          <!-- 磁盘卡片 -->
          <el-card class="monitor-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">磁盘</span>
              </div>
            </template>
            <div class="disk-list">
              <div v-for="(disk, index) in disks" :key="index" class="disk-item">
                <div class="disk-info">
                  <div class="disk-name">{{ disk.deviceName || '未命名' }}</div>
                  <div class="disk-size">{{ disk.total || 0 }} GB</div>
                </div>
                <el-progress :percentage="disk.usage || 0" :color="getDiskColor(disk.usage)" :show-text="true" />
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <!-- 磁盘吞吐量 -->
          <el-card class="monitor-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">磁盘吞吐量</span>
              </div>
            </template>
            <div class="throughput-items">
              <div class="throughput-item">
                <el-icon class="throughput-icon read"><Top /></el-icon>
                <span class="throughput-label">读取/秒</span>
                <span class="throughput-value">{{ formatBytesRate(monitorHost.ioReadBytesRate) }}</span>
              </div>
              <div class="throughput-item">
                <el-icon class="throughput-icon write"><Bottom /></el-icon>
                <span class="throughput-label">写入/秒</span>
                <span class="throughput-value">{{ formatBytesRate(monitorHost.ioWriteBytesRate) }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <!-- 网络信息卡片 -->
          <el-card class="monitor-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">网络</span>
              </div>
            </template>
            <div class="network-content">
              <div class="network-item">
                <div class="network-info">
                  <el-icon class="network-icon upload"><Top /></el-icon>
                  <span class="network-label">上行速率/秒</span>
                </div>
                <span class="network-value upload">{{ formatBytesRate(monitorHost.networkSentRate) }}</span>
              </div>
              <div class="network-item">
                <div class="network-info">
                  <el-icon class="network-icon download"><Bottom /></el-icon>
                  <span class="network-label">下行速率/秒</span>
                </div>
                <span class="network-value download">{{ formatBytesRate(monitorHost.networkRecvRate) }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 监控图表内容 -->
    <div v-if="activeTab === 'chart'" class="chart-content">
      <!-- 时间选择和手动刷新 -->
      <div class="time-selector">
        <el-radio-group v-model="timeRange" @change="handleTimeRangeChange">
          <el-radio-button label="30min">最近30分钟</el-radio-button>
          <el-radio-button label="24h">最近24小时</el-radio-button>
          <el-radio-button label="3day">最近3天</el-radio-button>
        </el-radio-group>
        <el-button icon="Refresh" @click="loadChartData" style="margin-left:16px;margin-top: 10px;">刷新</el-button>
      </div>
      <!-- 监控图表 -->
      <div class="chart-container">
        <!-- CPU使用率图表 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">CPU使用率</span>
            </div>
          </template>
          <div class="chart-content">
            <div ref="cpuChart" style="height: 300px;"></div>
          </div>
        </el-card>
        <!-- 内存使用率图表 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">内存使用率</span>
            </div>
          </template>
          <div class="chart-content">
            <div ref="memoryChart" style="height: 300px;"></div>
          </div>
        </el-card>
        <!-- 磁盘使用率图表 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">磁盘使用率</span>
            </div>
          </template>
          <div class="chart-content">
            <div ref="diskChart" style="height: 300px;"></div>
          </div>
        </el-card>
        <!-- 网络流量图表 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">网络流量</span>
            </div>
          </template>
          <div class="chart-content">
            <div ref="networkChart" style="height: 300px;"></div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup name="MonitorHostDetail">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getHostDetail, getHostChartData } from '@/api/monitor/host'
import { Top, Bottom } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const hostId = route.params.hostId
const hostInfo = ref({})
const monitorHost = ref({})
const disks = ref([])
const hostAttr = ref({})
const activeTab = ref('overview')
const timeRange = ref('30min')
const loading = ref(false)
let refreshInterval = null

// 图表相关
const cpuChart = ref(null)
const memoryChart = ref(null)
const diskChart = ref(null)
const networkChart = ref(null)
let cpuChartInstance = null
let memoryChartInstance = null
let diskChartInstance = null
let networkChartInstance = null

const switchTab = (tab) => {
  activeTab.value = tab
  if (tab === 'chart') {
    nextTick(() => {
      initCharts()
      loadChartData()
    })
  } else if (tab === 'overview') {
    getHostInfo()
  }
}

const getHostInfo = async () => {
  try {
    loading.value = true
    const response = await getHostDetail(hostId)
    hostInfo.value = response.data.host
    hostAttr.value = response.data.hostAttr
    monitorHost.value = response.data.monitorHost
    if (monitorHost.value.diskJson) {
      try {
        disks.value = JSON.parse(monitorHost.value.diskJson)
      } catch {
        disks.value = []
      }
    }
  } catch (error) {
    console.error('获取主机详情失败:', error)
    ElMessage.error('获取主机详情失败')
  } finally {
    loading.value = false
  }
}

// 格式化字节速率
const formatBytesRate = (rate) => {
  if (!rate || rate === 0) return '0 B/s'
  
  const units = ['B/s', 'KB/s', 'MB/s', 'GB/s']
  let value = Number(rate)
  let unitIndex = 0
  
  while (value >= 1024 && unitIndex < units.length - 1) {
    value /= 1024
    unitIndex++
  }
  
  return `${value.toFixed(2)} ${units[unitIndex]}`
}

const formatUpdateTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

const handleTimeRangeChange = () => {
  loadChartData()
}

const initCharts = () => {
  if (cpuChart.value) {
    cpuChartInstance = echarts.init(cpuChart.value)
    memoryChartInstance = echarts.init(memoryChart.value)
    diskChartInstance = echarts.init(diskChart.value)
    networkChartInstance = echarts.init(networkChart.value)
  }
}

const loadChartData = async () => {
  try {
    const response = await getHostChartData(hostId, timeRange.value)
    const chartData = response.data
    
    if (chartData.timeData && chartData.timeData.length > 0) {
      // 使用真实数据
      initCPUChart(chartData.timeData, chartData.cpuData)
      initMemoryChart(chartData.timeData, chartData.memoryData)
      initDiskChart(chartData.timeData, chartData.diskData)
      initNetworkChart(chartData.timeData, chartData.networkUploadData, chartData.networkDownloadData)
    } else {
      // 如果没有数据，显示空图表
      const emptyTimeData = []
      const emptyData = []
      initCPUChart(emptyTimeData, emptyData)
      initMemoryChart(emptyTimeData, emptyData)
      initDiskChart(emptyTimeData, emptyData)
      initNetworkChart(emptyTimeData, emptyData, emptyData)
    }
  } catch (error) {
    console.error('获取图表数据失败:', error)
    ElMessage.error('获取图表数据失败')
    
    // 模拟数据作为备用
    // const timeData = generateTimeData()
    // const cpuData = generateRandomData(30, 0, 100)
    // const memoryData = generateRandomData(30, 0, 100)
    // const diskData = generateRandomData(30, 0, 100)
    // const networkUploadData = generateRandomData(30, 0, 1000)
    // const networkDownloadData = generateRandomData(30, 0, 1000)
    
    // initCPUChart(timeData, cpuData)
    // initMemoryChart(timeData, memoryData)
    // initDiskChart(timeData, diskData)
    // initNetworkChart(timeData, networkUploadData, networkDownloadData)
  }
}

const generateTimeData = () => {
  const data = []
  const now = new Date()
  for (let i = 29; i >= 0; i--) {
    const time = new Date(now.getTime() - i * 60 * 1000)
    data.push(`${time.getHours()}:${time.getMinutes().toString().padStart(2, '0')}`)
  }
  return data
}

const generateRandomData = (count, min, max) => {
  const data = []
  for (let i = 0; i < count; i++) {
    data.push(Number((Math.random() * (max - min) + min).toFixed(2)))
  }
  return data
}

const initCPUChart = (timeData, cpuData) => {
  if (!cpuChartInstance) return
  const option = {
    tooltip: { trigger: 'axis' },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { 
      type: 'category', 
      boundaryGap: false, 
      data: timeData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: { 
      type: 'value', 
      axisLabel: { formatter: '{value}%' }, 
      max: 100 
    },
    series: [{
      name: 'CPU使用率', 
      type: 'line', 
      smooth: true, 
      data: cpuData,
      itemStyle: { color: '#5470c6' },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(84, 112, 198, 0.5)' },
          { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
        ])
      }
    }]
  }
  cpuChartInstance.setOption(option)
}

const initMemoryChart = (timeData, memoryData) => {
  if (!memoryChartInstance) return
  const option = {
    tooltip: { trigger: 'axis' },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { 
      type: 'category', 
      boundaryGap: false, 
      data: timeData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: { 
      type: 'value', 
      axisLabel: { formatter: '{value}%' }, 
      max: 100 
    },
    series: [{
      name: '内存使用率', 
      type: 'line', 
      smooth: true, 
      data: memoryData,
      itemStyle: { color: '#91cc75' },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(145, 204, 117, 0.5)' },
          { offset: 1, color: 'rgba(145, 204, 117, 0.1)' }
        ])
      }
    }]
  }
  memoryChartInstance.setOption(option)
}

const initDiskChart = (timeData, diskData) => {
  if (!diskChartInstance) return
  const option = {
    tooltip: { trigger: 'axis' },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { 
      type: 'category', 
      boundaryGap: false, 
      data: timeData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: { 
      type: 'value', 
      axisLabel: { formatter: '{value}%' }, 
      max: 100 
    },
    series: [{
      name: '磁盘使用率', 
      type: 'line', 
      smooth: true, 
      data: diskData,
      itemStyle: { color: '#fac858' },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(250, 200, 88, 0.5)' },
          { offset: 1, color: 'rgba(250, 200, 88, 0.1)' }
        ])
      }
    }]
  }
  diskChartInstance.setOption(option)
}

const initNetworkChart = (timeData, uploadData, downloadData) => {
  if (!networkChartInstance) return
  const option = {
    tooltip: { trigger: 'axis' },
    legend: { data: ['上行速率', '下行速率'] },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: { 
      type: 'category', 
      boundaryGap: false, 
      data: timeData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: { 
      type: 'value', 
      axisLabel: { formatter: '{value} kb/s' } 
    },
    series: [
      { 
        name: '上行速率', 
        type: 'line', 
        smooth: true, 
        data: uploadData, 
        itemStyle: { color: '#ee6666' } 
      },
      { 
        name: '下行速率', 
        type: 'line', 
        smooth: true, 
        data: downloadData, 
        itemStyle: { color: '#5470c6' } 
      }
    ]
  }
  networkChartInstance.setOption(option)
}

const handleResize = () => {
  cpuChartInstance?.resize()
  memoryChartInstance?.resize()
  diskChartInstance?.resize()
  networkChartInstance?.resize()
}

const getCpuColor = (percentage) => {
  const value = parseFloat(percentage) || 0
  if (value < 50) return '#67C23A'
  if (value < 80) return '#E6A23C'
  return '#F56C6C'
}

const getMemoryColor = (percentage) => {
  const value = parseFloat(percentage) || 0
  if (value < 60) return '#67C23A'
  if (value < 80) return '#E6A23C'
  return '#F56C6C'
}

const getDiskColor = (percentage) => {
  const value = parseFloat(percentage) || 0
  if (value < 70) return '#67C23A'
  if (value < 85) return '#E6A23C'
  return '#F56C6C'
}

const handleBack = () => {
  router.push('/monitor/monitorhost')
}

const refreshData = () => {
  if (activeTab.value === 'overview') {
    getHostInfo()
  } else {
    loadChartData()
  }
}

// 设置定时刷新
const setupAutoRefresh = () => {
  // 清除现有定时器
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
  
  // 设置新的定时器，每分钟刷新一次
  refreshInterval = setInterval(() => {
    refreshData()
  }, 60000) // 60秒 = 60000毫秒
}

onMounted(() => {
  getHostInfo()
  setupAutoRefresh()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 清除定时器
  if (refreshInterval) {
    clearInterval(refreshInterval)
    refreshInterval = null
  }
  
  window.removeEventListener('resize', handleResize)
  cpuChartInstance?.dispose()
  memoryChartInstance?.dispose()
  diskChartInstance?.dispose()
  networkChartInstance?.dispose()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
}

/* 顶部选项卡样式 */
.tab-header {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.tab-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
}

.tab-button {
  min-width: 100px;
}

.host-status {
  display: flex;
  justify-content: flex-end;
  text-align: right;
  align-items: center;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  gap: 16px;
}

.agent-status {
  display: flex;
  align-items: center;
  gap: 12px;
}

.agent-version, .update-time {
  font-size: 12px;
  color: #909399;
}

/* 主体内容样式 */
.detail-content {
  margin-top: 10px;
}

.info-card, .monitor-card {
  margin-bottom: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-subtitle {
  font-size: 14px;
  color: #409EFF;
}

.info-list {
  padding: 10px 0;
}

.info-item {
  margin-bottom: 18px;
  font-size: 16px;
  display: flex;
  gap: 12px;
}

.label {
  color: #909399;
  min-width: 70px;
  text-align: right;
}

.value {
  color: #303133;
  flex: 1;
}

.cpu-content, .memory-content {
  padding: 12px 0;
}

.cpu-item {
  margin-bottom: 18px;
  font-size: 16px;
}

.memory-main {
  display: flex;
  align-items: center;
  gap: 24px;
}

.memory-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.memory-used, .memory-percent {
  font-size: 16px;
}

.memory-total {
  margin-top: 12px;
  font-size: 15px;
  color: #909399;
}

.connection-content {
  padding: 10px 0;
}

.connection-item {
  margin-bottom: 18px;
  font-size: 16px;
}

.connection-item.total {
  font-weight: bold;
  color: #409EFF;
}

.disk-list {
  margin-top: 12px;
}

.disk-item {
  margin-bottom: 18px;
}

.disk-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.disk-name {
  font-size: 15px;
  color: #303133;
}

.disk-size {
  font-size: 14px;
  color: #909399;
}

.throughput-items, .iops-items, .network-content {
  padding: 10px 0;
}

.throughput-item, .iops-item, .network-item {
  margin-bottom: 18px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.throughput-label, .iops-label, .network-label {
  font-size: 15px;
  color: #606266;
}

.throughput-value, .iops-value, .network-value {
  font-size: 15px;
  color: #303133;
}

.throughput-icon.read {
  color: #67C23A;
}

.throughput-icon.write {
  color: #F56C6C;
}

.network-icon.upload {
  color: #67C23A;
}

.network-icon.download {
  color: #F56C6C;
}

/* 图表内容样式 */
.chart-content {
  padding: 0;
}

.time-selector {
  margin-bottom: 20px;
  text-align: center;
}

.chart-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.chart-card {
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .detail-content {
    display: block;
  }
  .el-row {
    flex-direction: column;
  }
  .chart-container {
    grid-template-columns: 1fr;
  }
  .host-status {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>